package com.netintech.project.system.ffmpeg;

import lombok.extern.slf4j.Slf4j;
import net.bramp.ffmpeg.FFmpeg;
import net.bramp.ffmpeg.builder.FFmpegBuilder;
import net.bramp.ffmpeg.builder.FFmpegOutputBuilder;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class FfmpegUtil {

    /**
     * 管理每个操作ffmpeg的线程
     */
    private static Map<UUID, Process> map = new ConcurrentHashMap<>(8);

    /**
     * @param ffmpegPath
     * @param transportType "tcp" or "udp"
     * @param rtspUrl
     * @param outputPath
     * @param uuid
     * @param seconds
     * @throws IOException
     * @throws InterruptedException
     */
    public static void execute(String ffmpegPath, String transportType, String rtspUrl, String outputPath, UUID uuid, Integer seconds
            , String ffmpegOutputDirPath) throws IOException, InterruptedException {

//        设置输出
        FFmpegOutputBuilder outputBuilder = new FFmpegOutputBuilder()
                .setFilename(outputPath);

//        设置执行参数
        FFmpegBuilder builder = new FFmpegBuilder()
//                todo
                .addExtraArgs("-rtsp_transport", transportType)
                .setInput(rtspUrl)
                .overrideOutputFiles(true)
                .addOutput(outputBuilder);

//        设置Process 命令行
        List<String> args1 = new ArrayList<>();
        args1.add(ffmpegPath);
        List<String> params = builder.build();
        args1.addAll(params);
        log.info("ffmpeg执行参数-->" + StringUtils.join(params, " "));
        ProcessBuilder processBuilder = new ProcessBuilder(args1);
        processBuilder.redirectErrorStream(true);
//        设置子进程工作目录，这里用于配合修改后的ffmpeg源码，指定seqNum文件输出路径
        processBuilder.directory(new File(ffmpegOutputDirPath));

//        执行命令
        Process p = processBuilder.start();
        map.put(uuid, p);

//        延迟关闭
        Thread.sleep(seconds);
        if (p.isAlive()) {
            p.destroy();
        }
        map.remove(uuid);
    }
}
